package com.hiyee.zuul.filter;

import com.hiyee.grace.result.ResponseJsonResult;
import com.hiyee.utils.IPUtil;
import com.hiyee.utils.JsonUtils;
import com.hiyee.utils.RedisOperator;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@RefreshScope
public class BlackListFilter extends ZuulFilter {

//    blackIP:
//    continueCounts: 10
//    timeInterval: 10
//    time: 15

    @Autowired
    private RedisOperator redisOperator;

    @Value("${blackIP.continueCounts}")
    private Integer continueCounts;
    @Value("${blackIP.timeInterval}")
    private Integer timeInterval;
    @Value("${blackIP.time}")
    private Integer limitTime;



    /**
     * 过滤器的类型
     * pre
     * route
     * post
     * error
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 顺序 从小大大
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否开启过滤器
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器处理
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("进入到 zuul filter：BlackListFilter");
        // 获取上下文 请求对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest httpRequest = requestContext.getRequest();
        String ip = IPUtil.getRequestIp(httpRequest);

        final String ipRedisKey = "zuul_black_ip_" + ip;
        final String ipRedisLeftTimeKey = "zuul_black_ip_limit" + ip;

        System.out.println("continueCounts: " + continueCounts);

        long leftTime = redisOperator.ttl(ipRedisKey);
        System.out.println(leftTime);
        if(leftTime > 0) {
            stopRequest(requestContext);
            return null;
        }

        long times = redisOperator.increment(ipRedisLeftTimeKey, 1);
        if(times == 1) {
            redisOperator.expire(ipRedisKey, timeInterval);
        }

        if(times > continueCounts) {
            redisOperator.set(ipRedisKey, ipRedisKey, limitTime);
            stopRequest(requestContext);
        }
        return null;
    }

    private void stopRequest(RequestContext requestContext) {
        // 停止 zuul 继续向下路由，禁止请求通信
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(200);
        String response = JsonUtils.objectToJson(ResponseJsonResult.error("请求繁忙，请稍后重试！"));
        requestContext.setResponseBody(response);
        requestContext.getResponse().setCharacterEncoding("utf-8");
        requestContext.getResponse().setContentType(MediaType.APPLICATION_JSON_VALUE);
    }
}
